package com.wl.dzt.sys.core.dao.util;

import com.wl.dzt.sys.util.FieldUtil;
import com.wl.dzt.sys.util.LogicUtil;
import org.springframework.cglib.beans.BeanMap;

/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/5/005
 * @description 实体对象操作
 */
public class EntityUtil {

    /**
     * <b>获取id</b>
     * <p>
     * 得到某个实体的id属性
     * </p>
     *
     * @param entity
     * @return
     */
    public static String getId(Object entity) {
        BeanMap beanMap = BeanMap.create(entity);
        return LogicUtil.thenNull(beanMap.get("id"), null);
    }

    /**
     * <b> 是否存在ID</b>
     * <p>
     * 判断某个实体是否存在id这个属性
     * </p>
     *
     * @param entity
     * @return
     */
    public static Boolean exitId(Object entity) {
        return !LogicUtil.isNull(FieldUtil.doGetMethod(entity, "id"));
    }

    /**
     * <b>是否是个空实体</b>

     *
     * @param entity
     * @return
     */
    public static boolean isEmptyEntity(Object entity) {
        BeanMap beanMap = BeanMap.create(entity);
        int count = beanMap.size();
        for (Object key : beanMap.keySet()) {
            if (beanMap.get(key) == null)
                count--;
        }
        return count == 0;
    }

    /**
     * <b>存在id 但是其他字段没值 </b>
     * <p>
     * 判断某个实体是否存在id,并且其他字段没有值
     * </p>
     *
     * @param entity
     * @return
     */
    public static boolean idOtherFields(Object entity) {
        BeanMap beanMap = BeanMap.create(entity);
        int count = beanMap.size();
        for (Object key : beanMap.keySet()) {
            if (beanMap.get(key) == null)
                count--;
        }
        return (count == 1 && EntityUtil.exitId(entity));
    }

    /**
     * <b>设置id</b>
     * <p>
     * 设置某个实体的id属性
     * </p>
     *
     * @param entity
     * @param id
     */
    public static void setId(Object entity, String id) {
        BeanMap beanMap = BeanMap.create(entity);
        beanMap.put("id", id);
    }
}
